import axios from 'axios'
import { Notification, MessageBox, Loading } from 'element-ui'
import { getToken } from '@/utils/auth'
import Config from '@/settings'
import Cookies from 'js-cookie'

// 创建axios实例
// console.log(process.env.NODE_ENV)
// console.log(process.env.VUE_APP_BASE_API)
const service = axios.create({
  baseURL: '/cpd', // api 的 base_url
  // baseURL: '/defi', // api 的 base_url
  timeout: Config.timeout // 请求超时时间
})
// request拦截器
service.interceptors.request.use(
  config => {
    // console.log(config,222222)

    if (getToken()) {
      config.url=`${config.url}?cpd_session_id=${getToken()}`
      // config.headers['cpd_session_id'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      // console.log(111,getToken())
    }
    // config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      Notification.error({
        title: response.message
      })
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    let code = 0
    try {
      code = error.response.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        Notification.error({
          title: '网络请求超时',
          duration: 5000
        })
        return Promise.reject(error)
      }
    }
    switch (code) {
      case 400:
        error.message = '请求错误'
        break
      case 401:
        MessageBox.confirm(
          '登录状态已过期，您可以继续留在该页面，或者重新登录',
          '系统提示',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          Cookies.remove('cpd_session_id')
          // store.dispatch('LogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
          // })
        })
        break
      case 403:
        error.message = '拒绝访问'
        break
      case 404:
        error.message = `请求地址出错: ${error.response.config.url}`
        break
      case 408:
        error.message = '请求超时'
        break
      case 500:
        if (error.response.data.msg) {
          error.message = error.response.data.msg
        } else {
          error.message = '服务器内部错误'
        }
        break
      case 501:
        error.message = '服务未实现'
        break
      case 502:
        error.message = '网关错误'
        break
      case 503:
        error.message = '服务不可用'
        break
      case 504:
        error.message = '网关超时'
        break
      case 505:
        error.message = 'HTTP版本不受支持'
        break
      default:
        error.message = '请求未知错误'
        break
    }
    Notification.error({
      title: '接口请求失败',
      duration: 5000,
      message: error.message
    })
    return Promise.reject(error)
  }
)

export default ({ url, data, method, params, headers = {}, extraConfig = {}}) => {
  const { loading = true, showError = true } = extraConfig
  const loadingService = loading ? Loading.service({
    fullscreen: true,
    text: '加载中,请稍后'
  }) : null
  return new Promise((resolve, reject) => {
    service.request({
      url, method, params, data, headers
    }).then(res => {
      loading && loadingService.close()
      if (res.code != 0 && showError) {
        Notification.error({
          title: '错误',
          message: res.message
        })
      }
      resolve(res)
    }).catch(err => {
      loading && loadingService.close()
      reject(err)
    })
  })
}
// export default service
